<template>
  <div class="data-rule">
    <eForm labelPosition="left" :labelWidth="50">
      <eFormItem label="必填">
        <eSwitch v-model="rules.required"></eSwitch>
      </eFormItem>
      <eInput class="pattern-input" placeholder="请填写正则表达式" v-model="rules.pattern"></eInput>
      <eInput class="pattern-input" placeholder="校验失败提示" v-model="rules.patternErrorMsg"></eInput>
      <CodeEditor label="校验函数" v-model="rules.validFunc" :tip="ruleValidFuncTip"></CodeEditor>
    </eForm>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, watch } from 'vue'
  import { ruleValidFuncTip } from '@/hooks/viewEditor/useTips'

  interface Iprops {
    modelValue: any
  }

  const props = defineProps<Iprops>()
  const emit = defineEmits<{
    (e: 'update:modelValue', data: Record<string, any>): void
  }>()

  const rules = reactive({
    required: false,
    pattern: '',
    patternErrorMsg: '',
    validFunc: ''
  })

  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        rules.required = newVal.required
        rules.pattern = newVal.pattern
        rules.patternErrorMsg = newVal.patternErrorMsg
        rules.validFunc = newVal.validFunc
      }
    },
    { immediate: true, deep: true }
  )

  watch(
    () => rules,
    (newVal) => {
      emit('update:modelValue', newVal)
    },
    { deep: true }
  )

</script>

<style lang="less" scoped>
  .data-rule {
    width: 100%;
    .pattern-input {
      margin-top: 12px;
    }
  }
</style>